package aufgabe3_chat;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;


public class Client_UDP_send{
	
	private DatagramSocket serverSocket;
	private Chat_User_Administration data;
	private Client_TCP client_tcp;
	private Logger logger;
	private final int PACKETSIZE;
	boolean broadcast;
	int port = 50001;
	
	public Client_UDP_send(Chat_User_Administration clientdata, DatagramSocket udpSocket, Client_TCP client_tcp, Logger logger, int packetsize){	
		this.client_tcp = client_tcp;
		serverSocket = udpSocket;
		data = clientdata;
		this.broadcast = false;
		this.logger = logger;
		logger.log("Client_UDP_send", "Constuctor", "Objekt Erzeugt");
		this.PACKETSIZE = packetsize;
	}
	
	public void send(String text)
    {
		
        byte[] sendData = new byte[PACKETSIZE];
        
        String username = client_tcp.getUserName();
        
        if(username == null){
        	return;
        }
        
        String massage = username;
        massage = massage + ": " + text;
        logger.log("Client_UDP_send", "Send Massage", massage);
        massage = massage + "\n";
        try {
			sendData = massage.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}  
        
        for(String name : data.key_set()){
        	
        	String val = data.get_val(name);
        	
        	logger.log("Client_UDP_send", "To", val + " " + name);
        	
        	if(val.startsWith("/")){
        		name = name.replace("/", "");
        	}
        	
			try {
				
				InetAddress adress = InetAddress.getByName(name);
        	
				DatagramPacket sendPacket;
		
				sendPacket = new DatagramPacket(sendData, sendData.length, adress, port);
				serverSocket.send(sendPacket);
			} catch (SocketException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

           
        }
        
        
        
    } 
}
